package nix.hibernate;

import nix.utils.HibernateUtils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class DemoTransaction {

	/**
	 * 事务
	 */
	@Test
	public void fun1() {
		Configuration conf = new Configuration().configure();
		SessionFactory sessionFactory = conf.buildSessionFactory();
		Session session = sessionFactory.openSession();
		// 开启事务
		Transaction ts = session.beginTransaction();
		try {
			// 获得已打开的事务对象
			session.getTransaction();

			// 提交事务
			ts.commit();
		} catch (Exception e) {
			// 回滚事务
			ts.rollback();
			session.close();
			sessionFactory.close();
		}
	}
	
	@Test
	public void fun2() {
		Session session = HibernateUtils.getCurrentSession();
		// 开启事务
		Transaction ts = session.beginTransaction();
		Session session2 = HibernateUtils.getCurrentSession();
		// 提交事务
		ts.commit();
		Session session3 = HibernateUtils.getCurrentSession();
		// 事务关闭时，会自动关闭当前线程关联的Session
		System.out.println(session == session2);// true
		System.out.println(session == session3);// false
		session.close();
	}
}
